import apiClient from './client'
import type {
  Shoes,
  ProductQuery,
  Brand,
  Types,
  PageResult,
  ProductVO,
  ProductSearchQuery,
  Color,
  Size,
  ProductImage,
} from '@/types'

export const productService = {
  // ===== 前台商品查询模块 (/api/v1/product) =====

  // 搜索商品（支持筛选与排序）
  searchProducts: (
    keyword: string,
    page: number = 1,
    size: number = 20,
    options: Partial<ProductSearchQuery> = {},
  ) =>
    apiClient.post<PageResult<ProductVO>>('/api/v1/product/search', {
      keyword,
      page,
      size,
      ...options,
    }),

  // 获取商品详情
  getProductDetail: (productId: number) =>
    apiClient.get<ProductVO>(`/api/v1/product/detail/${productId}`),

  // 获取相关推荐商品
  getRelatedProducts: (productId: number, size: number = 4) =>
    apiClient.get<ProductVO[]>(`/api/v1/product/related/${productId}`, {
      params: { size },
    }),

  // 获取商品列表 - 使用product接口支持完整筛选功能
  getProductList: (query: ProductQuery) =>
    apiClient.post<PageResult<ProductVO>>('/api/v1/product/list', query),

  // 获取品牌列表
  getProductBrands: () => apiClient.get<Brand[]>('/api/v1/product/brands'),

  // 获取商品类型列表
  getProductTypes: () => apiClient.get<Types[]>('/api/v1/product/types'),

  // 获取颜色列表
  getProductColors: () => apiClient.get<Color[]>('/api/v1/product/colors'),

  // 获取尺寸列表
  getProductSizes: () => apiClient.get<Size[]>('/api/v1/product/sizes'),

  // ===== 产品(鞋类)管理模块 (/api/v1/shoes) =====

  // 获取所有产品列表
  getAllShoes: () => apiClient.get<Shoes[]>('/api/v1/shoes/list'),

  // 分页查询产品列表
  getShoesListPage: (page: number = 1, size: number = 20, keyword?: string) =>
    apiClient.get<PageResult<Shoes>>('/api/v1/shoes/list/page', {
      params: { pageNum: page, pageSize: size, keyword },
    }),

  // 根据ID获取产品详情
  getShoesDetail: (shoeId: number) => apiClient.get<Shoes>(`/api/v1/shoes/${shoeId}`),

  // 添加新产品
  addShoes: (shoesData: Partial<Shoes>) => apiClient.post<Shoes>('/api/v1/shoes/add', shoesData),

  // 更新产品信息
  updateShoes: (shoesData: Partial<Shoes>) =>
    apiClient.post<boolean>('/api/v1/shoes/update', shoesData),

  // 删除产品
  deleteShoes: (shoeId: number) => apiClient.post(`/api/v1/shoes/delete/${shoeId}`),

  // 搜索产品
  searchShoes: (keyword: string) =>
    apiClient.get<Shoes[]>('/api/v1/shoes/search', { params: { keyword } }),

  // 修改产品状态
  updateShoesStatus: (shoeId: number, status: string) =>
    apiClient.post(`/api/v1/shoes/status/${shoeId}`, undefined, { params: { status } }),

  // 上传商品图片
  uploadShoesImage: (shoeId: number, file: File, imageType: string = 'product', isMain: boolean = false) => {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('imageType', imageType)
    formData.append('isMain', isMain.toString())
    return apiClient.post<ProductImage>(`/api/v1/shoes/upload-image/${shoeId}`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
  },

  // 批量上传商品图片
  uploadShoesImages: (shoeId: number, files: File[]) => {
    const formData = new FormData()
    files.forEach((file) => formData.append('files', file))
    return apiClient.post<ProductImage[]>(`/api/v1/shoes/upload-images/${shoeId}`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
  },

  // 获取商品图片列表
  getShoesImages: (shoeId: number) =>
    apiClient.get<ProductImage[]>(`/api/v1/shoes/${shoeId}/images`),

  // 删除商品图片
  deleteShoesImage: (shoeId: number, imageId: number) =>
    apiClient.post(`/api/v1/shoes/delete-image/${imageId}`),

  // 设置主图
  setShoesMainImage: (shoeId: number, imageId: number) =>
    apiClient.post(`/api/v1/shoes/set-main-image/${imageId}`),

  // ===== 品牌管理模块 (/api/brands) =====

  // 获取所有品牌列表
  getBrandsList: () => apiClient.get<Brand[]>('/api/brands'),

  // 分页查询品牌列表
  getBrandsListPage: (page: number = 1, size: number = 10, keyword?: string, status?: number) =>
    apiClient.get<PageResult<Brand>>('/api/brands/list/page', {
      params: { page, size, keyword, status },
    }),

  // 获取启用状态的品牌列表
  getActiveBrands: () => apiClient.get<Brand[]>('/api/brands/active'),

  // 根据ID获取品牌详情
  getBrandDetail: (brandId: number) => apiClient.get<Brand>(`/api/brands/${brandId}`),

  // 添加新品牌
  addBrand: (brandData: Partial<Brand>) => apiClient.post<Brand>('/api/brands', brandData),

  // 更新品牌信息
  updateBrand: (brandId: number, brandData: Partial<Brand>) =>
    apiClient.post<Brand>(`/api/brands/update/${brandId}`, brandData),

  // 删除品牌
  deleteBrand: (brandId: number) => apiClient.post(`/api/brands/delete/${brandId}`),

  // ===== 类型管理模块 (/api/types) =====

  // 获取所有类型列表
  getTypesList: () => apiClient.get<Types[]>('/api/types'),

  // 分页查询类型列表
  getTypesListPage: (page: number = 1, size: number = 10, keyword?: string, status?: string) =>
    apiClient.get<PageResult<Types>>('/api/types/list/page', {
      params: { page, size, keyword, status },
    }),

  // 获取启用状态的类型列表
  getActiveTypes: () => apiClient.get<Types[]>('/api/types/active'),

  // 根据ID获取类型详情
  getTypeDetail: (typeId: number) => apiClient.get<Types>(`/api/types/${typeId}`),

  // 添加新类型
  addType: (typeData: Partial<Types>) => apiClient.post<Types>('/api/types', typeData),

  // 更新类型信息
  updateType: (typeId: number, typeData: Partial<Types>) =>
    apiClient.post<Types>(`/api/types/update/${typeId}`, typeData),

  // 删除类型
  deleteType: (typeId: number) => apiClient.post(`/api/types/delete/${typeId}`),

  // ===== 颜色管理模块 (/api/colors) =====

  // 获取所有颜色列表
  getColorsList: () => apiClient.get<Color[]>('/api/colors'),

  // 分页查询颜色列表
  getColorsListPage: (page: number = 1, size: number = 10, keyword?: string, status?: number) =>
    apiClient.get<PageResult<Color>>('/api/colors/list/page', {
      params: { page, size, keyword, status },
    }),

  // 获取启用状态的颜色列表
  getActiveColors: () => apiClient.get<Color[]>('/api/colors/active'),

  // 根据ID获取颜色详情
  getColorDetail: (colorId: number) => apiClient.get<Color>(`/api/colors/${colorId}`),

  // 添加新颜色
  addColor: (colorData: Partial<Color>) => apiClient.post<boolean>('/api/colors', colorData),

  // 更新颜色信息
  updateColor: (colorId: number, colorData: Partial<Color>) =>
    apiClient.post<boolean>(`/api/colors/update/${colorId}`, colorData),

  // 删除颜色
  deleteColor: (colorId: number) => apiClient.post(`/api/colors/delete/${colorId}`),

  // ===== 尺寸管理模块 (/api/v1/sizes) =====

  // 获取所有尺寸列表
  getSizesList: () => apiClient.get<Size[]>('/api/v1/sizes/list'),

  // 分页查询尺寸列表
  getSizesListPage: (page: number = 1, size: number = 10, keyword?: string, status?: string) =>
    apiClient.get<PageResult<Size>>('/api/v1/sizes/list/page', {
      params: { page, size, keyword, status },
    }),

  // 获取启用状态的尺寸列表
  getActiveSizes: () => apiClient.get<Size[]>('/api/v1/sizes/active'),

  // 根据ID获取尺寸详情
  getSizeDetail: (sizeId: number) => apiClient.get<Size>(`/api/v1/sizes/${sizeId}`),

  // 添加新尺寸
  addSize: (sizeData: Partial<Size>) => apiClient.post<boolean>('/api/v1/sizes/add', sizeData),

  // 更新尺寸信息
  updateSize: (sizeData: Partial<Size>) =>
    apiClient.post<boolean>('/api/v1/sizes/update', sizeData),

  // 删除尺寸
  deleteSize: (sizeId: number) => apiClient.post(`/api/v1/sizes/delete/${sizeId}`),

  // 检查尺寸是否被使用
  checkSizeUsage: (sizeId: number) => apiClient.get<boolean>(`/api/v1/sizes/check-usage/${sizeId}`),

  // ===== 库存管理模块 (/api/v1/stock) =====

  // 获取所有库存列表
  getStockList: () => apiClient.get<import('@/types').Stock[]>('/api/v1/stock/list'),

  // 分页查询库存列表
  getStockListPage: (page: number = 1, size: number = 10, keyword?: string, shoeId?: number, sizeId?: number, colorId?: number) =>
    apiClient.get<PageResult<import('@/types').Stock>>('/api/v1/stock/list/page', {
      params: { page, size, keyword, shoeId, sizeId, colorId },
    }),

  // 根据产品ID获取库存列表
  getStockListByProduct: (productId: number) =>
    apiClient.get<import('@/types').Stock[]>(`/api/v1/stock/product/${productId}`),

  // 根据产品和尺寸查询库存
  getStockDetail: (productId: number, sizeId: number) =>
    apiClient.get<import('@/types').Stock>(`/api/v1/stock/product/${productId}/size/${sizeId}`),

  // 添加新库存
  addStock: (stockData: Partial<import('@/types').Stock>) =>
    apiClient.post<boolean>('/api/v1/stock/add', stockData),

  // 更新库存信息
  updateStock: (stockData: Partial<import('@/types').Stock>) =>
    apiClient.post<boolean>('/api/v1/stock/update', stockData),

  // 删除库存
  deleteStock: (shoeId: number, sizeId: number) =>
    apiClient.post(`/api/v1/stock/delete/${shoeId}/${sizeId}`),

  // ===== 商品图片管理模块 (/api/v1/product-images) =====

  // 根据商品ID获取图片列表
  getProductImages: (shoeId: number) =>
    apiClient.get<ProductImage[]>(`/api/v1/product-images/shoe/${shoeId}`),

  // 根据商品ID获取主图
  getProductMainImage: (shoeId: number) =>
    apiClient.get<ProductImage>(`/api/v1/product-images/main/${shoeId}`),

  // 添加商品图片
  addProductImage: (imageData: Partial<ProductImage>) =>
    apiClient.post<ProductImage>('/api/v1/product-images/add', imageData),

  // 批量添加商品图片
  batchAddProductImages: (imagesData: Array<Partial<ProductImage>>) =>
    apiClient.post<ProductImage[]>('/api/v1/product-images/batch-add', imagesData),

  // 更新商品图片
  updateProductImage: (imageData: Partial<ProductImage>) =>
    apiClient.put<boolean>('/api/v1/product-images/update', imageData),

  // 删除商品图片
  deleteProductImage: (imageId: number) =>
    apiClient.delete(`/api/v1/product-images/delete/${imageId}`),

  // 批量删除商品图片
  batchDeleteProductImages: (imageIds: number[]) =>
    apiClient.delete('/api/v1/product-images/batch-delete', { data: imageIds } as {
      data: number[]
    }),

  // 设置主图
  setProductMainImage: (imageId: number) =>
    apiClient.put(`/api/v1/product-images/set-main/${imageId}`),

  // 更新图片排序
  updateProductImageSort: (images: Array<Partial<ProductImage>>) =>
    apiClient.put<boolean>('/api/v1/product-images/update-sort', images),

  // 保存商品图片
  saveProductImages: (shoeId: number, images: Array<Partial<ProductImage>>) =>
    apiClient.post<boolean>(`/api/v1/product-images/save/${shoeId}`, images),

  // ===== 文件上传模块 (/api/v1/upload) =====

  // 上传图片
  uploadImage: (file: File) => apiClient.upload<string>('/api/v1/upload/image', file),
}

// 兼容性函数，用于现有组件
interface LegacyParams {
  categoryId?: number
  brandId?: number
  keyword?: string
  page?: number
  pageSize?: number
  filter?: string
  sortBy?: string
  sortOrder?: 'asc' | 'desc'
  [key: string]: string | number | boolean | null | undefined
}

export const getProductList = (params: LegacyParams) => {
  // 统一映射到 ProductQuery / ProductSearchQuery
  const page = params.page ?? 1
  const size = params.pageSize ?? 20

  // 排序映射
  let sortBy: ProductQuery['sortBy'] | undefined
  let sortOrder: ProductQuery['sortOrder'] | undefined
  const sortVal = (params.sortBy || '').toString()
  switch (sortVal) {
    case 'price-asc':
    case 'price_asc':
      sortBy = 'price'
      sortOrder = 'asc'
      break
    case 'price-desc':
    case 'price_desc':
      sortBy = 'price'
      sortOrder = 'desc'
      break
    case 'sales':
      sortBy = 'sales'
      sortOrder = 'desc'
      break
    case 'newest':
      sortBy = 'date'
      sortOrder = 'desc'
      break
  }

  // 根据 filter 的快捷含义设置默认排序
  if (!sortBy && params.filter) {
    if (params.filter === 'new') {
      sortBy = 'date'
      sortOrder = 'desc'
    }
    if (params.filter === 'hot') {
      sortBy = 'sales'
      sortOrder = 'desc'
    }
    if (params.filter === 'sale') {
      sortBy = 'price'
      sortOrder = 'asc'
    }
  }

  // 分类/品牌优先
  const query: ProductQuery = {
    page,
    size,
    ...(params.categoryId ? { typeId: params.categoryId } : {}),
    ...(params.brandId ? { brandId: params.brandId } : {}),
    ...(sortBy ? { sortBy } : {}),
    ...(sortOrder ? { sortOrder } : {}),
  }

  if (params.keyword && params.keyword.trim()) {
    // 搜索接口支持更多筛选字段
    const searchOptions: Partial<ProductSearchQuery> = {
      ...(query.brandId ? { brandId: query.brandId } : {}),
      ...(query.typeId ? { typeId: query.typeId } : {}),
      ...(sortBy ? { sortBy } : {}),
      ...(sortOrder ? { sortOrder } : {}),
    }
    return productService.searchProducts(params.keyword.trim(), page, size, searchOptions)
  }

  return productService.getProductList(query)
}

export default productService
